package ${package.Controller};

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
<#if isHaveUserField>
import com.dobest.<#if package.Controller?contains('userservice')>userservice.</#if>authsimp.interfaces.UserInterface;
</#if>
import com.dobest.common.vo.DbtComplexResult;
import com.dobest.common.vo.DbtResult;
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
<#if superControllerClassPackage??>
	import ${superControllerClassPackage};
</#if>
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;
import org.zhuzx.util.BizAssert;
import org.zhuzx.util.GeneralUtil;
import java.util.Arrays;

<#assign entityDeclaration = entity?uncap_first>
<#assign serviceDeclaration = '${table.serviceName?uncap_first}'>
<#assign REGEX_SEPARATOR = constants.UnifiedConstants.REGEX_PUNCTUATION_SEPARATION + '|表'>
<#assign moduleChName = table.comment?split(REGEX_SEPARATOR, 'r')[0]>
/**
 * ${moduleChName}
 * @author ${author}
 * @since ${date}
 */
@Api(tags = "${moduleChName}")
@RestController
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if><#if controllerMappingHyphenStyle>${controllerMappingHyphen}<#else>${entityDeclaration}</#if>")
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>

	@Autowired
	private ${table.serviceName} ${serviceDeclaration};
<#if isHaveUserField>
	@Autowired
	private UserInterface userInterface;
</#if>

	@ApiOperation("${moduleChName}-分页查询")
	@PostMapping(value = "/queryPage", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	public DbtComplexResult<${entity}> queryPage(
		<#if columnsMap['name']??>
			@ApiParam("名称（模糊搜索）") @RequestParam(required = false) String name,
		</#if>
			@ApiParam(value = "分页参数-当前是第几页（从1开始）", required = true) @RequestParam int currentPage,
			@ApiParam(value = "分页参数-一页的数据量", required = true) @RequestParam int pageSize) {
		Page<${entity}> page = new Page<>(currentPage, pageSize);
		${serviceDeclaration}.lambdaQuery()
		<#if columnsMap['name']??>
				.like(StringUtils.hasText(name), ${entity}::getName, name)
		</#if>
				.page(page);
		return DbtComplexResult.newSuccessResult(page.getRecords(), page.getTotal());
	}

	@ApiOperation("${moduleChName}-根据id获取单条")
	@GetMapping("/getById")
	public DbtComplexResult<${entity}> getById(@RequestParam Integer id) {
		${entity} one = ${serviceDeclaration}.getById(id);
		return DbtComplexResult.newSuccessResult(one);
	}

	@ApiOperation(value = "${moduleChName}-新增"<#if moduleChName?length + 2 < table.comment?length>, notes = "${MicroUtil.subBehind(table.comment, moduleChName)?keep_after('(' + REGEX_SEPARATOR + ')+', 'r')}"</#if>)
	@PostMapping(value = "/create", consumes = "application/json;charset=UTF-8")
	public DbtResult create(@Validated @RequestBody ${entity} ${entityDeclaration}) {
<#list columns as column>
	<#if column.getUniqueColumns()??>
		BizAssert.notAllow(${serviceDeclaration}.lambdaQuery()
			<#list column.getUniqueColumns() as uni>
				<#assign getter = 'get' + MicroUtil.convertUnderlineToCamelCased(uni)?cap_first/>
				.eq(${entity}::${getter}, ${entityDeclaration}.${getter}())
			</#list>
				.exists(), "已存在-<#list column.getUniqueColumnRemarks() as remark>${MicroUtil.subBeforeByRegex(remark, constants.UnifiedConstants.REGEX_PUNCTUATION_SEPARATION)}-</#list>相同的记录：" +
			<#if column.getUniqueColumns()?size == 1>
        	<#list column.getUniqueColumns() as uni><#assign getter = 'get' + MicroUtil.convertUnderlineToCamelCased(uni)?cap_first/>
				${entityDeclaration}.${getter}()</#list>);
            <#else>
				GeneralUtil.concatString("-", null<#list column.getUniqueColumns() as uni><#assign getter = 'get' + MicroUtil.convertUnderlineToCamelCased(uni)?cap_first/>, ${entityDeclaration}.${getter}()</#list>));
			</#if>
	<#break>
	</#if>
</#list>
	<#if isHaveUserField>
		${entityDeclaration}.setCreateUser(userInterface.getUserInfo().getUsername());
	</#if>
		${serviceDeclaration}.save(${entityDeclaration});
		return DbtResult.newSuccessResult();
	}

	@ApiOperation("${moduleChName}-修改")
	@PostMapping(value = "/update", consumes = "application/json;charset=UTF-8")
	public DbtResult update(@RequestBody ${entity} ${entityDeclaration}) {
		BizAssert.notNull(${entityDeclaration}.getId(), "请传入需要修改的记录的id");
<#list columns as column>
    <#if column.getUniqueColumns()??>
		BizAssert.notAllow(${serviceDeclaration}.lambdaQuery()
			<#list column.getUniqueColumns() as uni>
				<#assign getter = 'get' + MicroUtil.convertUnderlineToCamelCased(uni)?cap_first/>
				.eq(${entity}::${getter}, ${entityDeclaration}.${getter}())
			</#list>
				.ne(${entity}::getId, ${entityDeclaration}.getId())
				.exists(), "已存在-<#list column.getUniqueColumnRemarks() as remark>${MicroUtil.subBeforeByRegex(remark, constants.UnifiedConstants.REGEX_PUNCTUATION_SEPARATION)}-</#list>相同的记录：" +
			<#if column.getUniqueColumns()?size == 1>
				<#list column.getUniqueColumns() as uni><#assign getter = 'get' + MicroUtil.convertUnderlineToCamelCased(uni)?cap_first/>
				${entityDeclaration}.${getter}()</#list>);
			<#else>
				GeneralUtil.concatString("-", null<#list column.getUniqueColumns() as uni><#assign getter = 'get' + MicroUtil.convertUnderlineToCamelCased(uni)?cap_first/>, ${entityDeclaration}.${getter}()</#list>));
			</#if>
        <#break>
    </#if>
</#list>
	<#if isHaveUserField>
		${entityDeclaration}.setUpdateUser(userInterface.getUserInfo().getUsername());
	</#if>
		boolean success = ${serviceDeclaration}.updateById(${entityDeclaration});
		return DbtResult.newResult(success, "未匹配到id为" + ${entityDeclaration}.getId() + "的记录");
	}

	@ApiOperation(value = "${moduleChName}-批量删除", hidden = true)
	@GetMapping("/deleteBatch")
	public DbtResult deleteBatch(
			@ApiParam(value = "以英文逗号连接的多个id值", required = true) @RequestParam String ids) {
		BizAssert.mustTrue(ids.matches("[\\d,]"), "必须传入合法的主键id值（整型或者以英文逗号连接的多个整型）");
		${serviceDeclaration}.removeBatchByIds(Arrays.asList(ids.split(",")));
		return DbtResult.newSuccessResult();
	}

}